import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Chart from '../components/chart';
import Map from '../components/map';
import { removeCity } from '../actions/weather';

class WeatherList extends Component {
  constructor(props) {
    super(props);
    this.onRemoveButtonClick = this.onRemoveButtonClick.bind(this);
  }

  onRemoveButtonClick(item) {
    this.props.removeCity(item);
  }

  render() {
    if(this.props.weather.length == 0) {
      return (
        <div className="no-data bg-info">
          <p>没有数据呀</p>
        </div>
      )
    }
    return (
      <table className="table table-hover">
        <thead>
          <tr>
            <th className="cell-city">城市</th>
            <th>温度  (℃)</th>
            <th>气压 (hPa)</th>
            <th>体感 (%)</th>
            <th className="cell-map">地图</th>
          </tr>
        </thead>
        <tbody>
          { this.props.weather.map( (item) => {
            console.log(item);
            return (
              <tr key={item.city.id}>
                <td>
                  <div className="city-name">{item.city.name}/{item.city.country}</div>
                  <button onClick={() => {this.onRemoveButtonClick(item)}} className="btn btn-sm btn-block">
                    删除
                  </button>
                </td>
                <td>
                  <Chart data={item.list.map(d => { return d.main.temp - 273; })} color="red" units="℃" />
                </td>
                <td>
                    <Chart data={item.list.map(d => { return d.main.pressure; })} color="green" units="hPa"/>
                </td>
                <td>
                    <Chart data={item.list.map(d => { return d.main.humidity; })} color="blue" units="%"/>
                </td>
                <td>
                  <Map {...item.city.coord } zoom={8}/>
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    )
  }
}

function mapToStateProps({ weather }) {
  return { weather }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators( { removeCity }, dispatch);
}

export default connect(mapToStateProps, mapDispatchToProps)(WeatherList);
